package com.bkhech.boot.sample.mvc.auth;

import cn.hutool.core.util.ObjectUtil;
import com.bkhech.boot.configure.security.core.LoginUser;
import com.bkhech.boot.configure.security.core.api.auth.LoginUserApi;
import com.bkhech.boot.sample.mvc.accesstoken.oauth2.OAuth2TokenApi;
import com.bkhech.boot.sample.mvc.accesstoken.oauth2.dto.OAuth2AccessTokenCheckRespDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;

/**
 * 获取 LoginUser
 * @author guowm
 * @date 2023/2/8
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class LoginUserApiImpl implements LoginUserApi {
    private final OAuth2TokenApi oauth2TokenApi;
    @Override
    public LoginUser getLoginUser(String token) {
        try {
            OAuth2AccessTokenCheckRespDto accessToken = oauth2TokenApi.checkAccessToken(token);
            if (accessToken == null) {
                return null;
            }

            // 构建登录用户
            return new LoginUser().setId(accessToken.getUserId()).setTenantId(accessToken.getTenantId()).setScopes(accessToken.getScopes());
        } catch (Exception serviceException) {
            // 校验 Token 不通过时，考虑到一些接口是无需登录的，所以直接返回 null 即可
            return null;
        }
    }
}
